package com.bootcamp.mall.controller.mall;

/**
 * @program: mall
 * @author: Keyu Li
 * @create: 2021-11-12 15:11
 **/

import com.bootcamp.mall.model.Goods;
import com.bootcamp.mall.model.GoodsType;
import com.bootcamp.mall.model.Result;
import com.bootcamp.mall.model.bo.goods.GoodsBO;
import com.bootcamp.mall.model.bo.goods.MsgBO;
import com.bootcamp.mall.model.bo.malluser.UserSignupLoginBO;
import com.bootcamp.mall.model.vo.goods.GetCommentVO;
import com.bootcamp.mall.model.vo.goods.GoodsMsgVO;
import com.bootcamp.mall.model.vo.goods.GoodsVO;
import com.bootcamp.mall.model.vo.malluser.UserSignupLoginVO;
import com.bootcamp.mall.service.goods.GoodsService;
import com.bootcamp.mall.service.goods.GoodsServiceImpl;
import com.bootcamp.mall.utils.JSONUtil;
import com.bootcamp.mall.utils.StringUtil;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(name = "MallGoodsServlet", value = {"/api/mall/goods/*", "/api/mall/index/*"})
public class MallGoodsServlet extends HttpServlet {

    Gson gson = new Gson();
    GoodsService goodsService = new GoodsServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String op = request.getRequestURI().replace("/api/mall/", "");
        if ("index/getType".equals(op)) {
            opGetType(request, response);
        } else if ("goods/getGoodsByType".equals(op)) {
            opGetGoodsByType(request, response);
        } else if ("goods/searchGoods".equals(op)) {
            opSearchGoods(request, response);
        } else if ("goods/getGoodsInfo".equals(op)) {
            opGetGoodsInfo(request, response);
        } else if ("goods/getGoodsMsg".equals(op)) {
            opGetGoodsMsg(request, response);
        } else if ("goods/getGoodsComment".equals(op)) {
            opGetGoodsComment(request, response);
        }
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String op = request.getRequestURI().replace("/api/mall/", "");
        if ("goods/askGoodsMsg".equals(op)) {
            opAskGoodsMsg(request, response);
        }
    }

    private void opAskGoodsMsg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        // json解析四联：获取字符串，判断不为空，获取对象，捕获异常判断参数合法
        String jsonContent = JSONUtil.parseContent(request);
        // 合法性
        if (StringUtil.isEmpty(jsonContent)) {
            writer.println(gson.toJson(Result.error("前端异常！")));
            return;
        }
        // jsonContent 解析为 bo
        // json转换为AddGoodsBO对象
        JsonObject asJsonObject = new JsonParser().parse(jsonContent).getAsJsonObject();
        try {
            MsgBO msgBO = gson.fromJson(asJsonObject, MsgBO.class);
            // 添加到数据库
            Integer code = goodsService.addGoodsMsg(msgBO);
            if (code == 0) {
                writer.println(gson.toJson(Result.ok()));
                return;
            }
            writer.println(gson.toJson(Result.error("服务器异常！")));
        } catch (Exception e) {
            e.printStackTrace();
            writer.println(gson.toJson(Result.error("参数异常！")));
        }

    }


    private void opGetGoodsMsg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        // 获取id参数
        int id;
        try {
            id = Integer.parseInt(request.getParameter("id"));
        } catch (NumberFormatException e) {
            writer.println(gson.toJson(Result.error("前端参数异常")));
            return;
        }
        // 获取vo
        List<GoodsMsgVO> goodsMsgVOS = goodsService.getGoodsMsg(id);
        writer.println(gson.toJson(Result.ok(goodsMsgVOS)));
    }

    private void opGetGoodsComment(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        // 获取id参数
        int goodsId;
        try {
            goodsId = Integer.parseInt(request.getParameter("goodsId"));
        } catch (NumberFormatException e) {
            writer.println(gson.toJson(Result.error("前端参数异常")));
            return;
        }
        GetCommentVO getCommentVO = goodsService.getGoodsComment(goodsId);
        writer.println(gson.toJson(Result.ok(getCommentVO)));
    }


    private void opGetGoodsInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        // 获取id参数
        int id;
        try {
            id = Integer.parseInt(request.getParameter("id"));
        } catch (NumberFormatException e) {
            writer.println(gson.toJson(Result.error("前端参数异常")));
            return;
        }
        GoodsVO goodsVO = goodsService.getGoodsInfoFront(id);
        // 即便是null也正常输出就是了
        writer.println(gson.toJson(Result.ok(goodsVO)));
    }


    private void opSearchGoods(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 将keyword封装为bo进行查询（为了后续扩展性）
        String keyword = request.getParameter("keyword");
        Goods goods = new Goods();
        goods.setName(keyword);
        List<GoodsVO> goodsByTypeVOs = goodsService.searchGoods(goods);
        response.getWriter().println(gson.toJson(Result.ok(goodsByTypeVOs)));
    }


    private void opGetType(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 照搬 goodsService 中 api
        //TODO: 首页不显示 未分类 类目。
        List<GoodsType> goodsByTypeVOs = goodsService.getTypes();
        response.getWriter().println(gson.toJson(Result.ok(goodsByTypeVOs)));
    }


    private void opGetGoodsByType(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        // 获取参数
        int typeId;
        try {
            typeId = Integer.parseInt(request.getParameter("typeId"));
        } catch (NumberFormatException e) {
            writer.println(gson.toJson(Result.error("前端参数异常！")));
            return;
        }
        // 使用GoodsService api
        List<GoodsVO> goodsByTypes = goodsService.getGoodsByType(typeId);
        writer.println(gson.toJson(Result.ok(goodsByTypes)));
    }


}
